<?php

namespace Database;

/**
 * Description of Mysql
 *
 * @author E.Mylcin
 */
class Mysql extends \Database {

    private $link = false;

    public function __construct($params) {
        $this->px = isset($params['px']) ? $params['px'] : "";
        $server = isset($params['server']) ? $params['server'] : false;
        $user = isset($params['user']) ? $params['user'] : false;
        $password = isset($params['password']) ? $params['password'] : false;
        $dbname = isset($params['dbname']) ? $params['dbname'] : false;
        $queries = (isset($params['query']) && !empty($params['query'])) ? $params['query'] : false;

        $link = mysql_connect($server, $user, $password);
        if (!$link) {
            \Logger::error(mysql_error());
        } else {
            $db = mysql_select_db($dbname, $link);
            if (!$db) {
                \Logger::error(mysql_error($link));
            } else {
                $this->link = $link;
                if ($queries) {
                    foreach ($queries as $sql) {
                        $result = mysql_query($sql, $this->link);
                        if (!$result) {
                            \Logger::error(mysql_error($link));
                        }
                    }
                }
            }
        }
        return $this;
    }

    public function execute() {
        $sql = $this->getSql();
        $result = mysql_query($sql, $this->link);
        $this->data = false;
        $this->action = false;
        return new DBResult($result);
    }

}

class DBResult {

    private $result;

    public function __construct($result) {
        $this->result = $result;
    }

    function Fetch() {
        if ($this->result) {
            return mysql_fetch_assoc($this->result);
        } else {
            return false;
        }
    }

    public function __destruct() {
        $this->result = false;
    }

}
